﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using System.Web.Security;
using Bzure.Security;
using Bzure.Security.Permissions;
using Bzure.Security.Principal;
using Bzure.Apps.Security;
using Bzure.Apps.Security.ViewModels;
using Bzure.Common.Core;
using Bzure.Common.Text;


namespace Bzure.Apps.Security.Controllers
{
    [Export(typeof(IController)), ExportMetadata("Name", "Account"), ExportMetadata("Area", "SecurityApp")]
    public class AccountController : T4ViewController
    {
        MasterViewModel MasterViewModel = new ViewModels.MasterViewModel()
        {
            Title = "通用权限管理"
        };
        // **************************************
        // URL: /Account/LogOn
        // **************************************
        [SecurityAppFilter(PageControllerItems.LogonController)]
        public ActionResult LogOn()
        {
            string msg = string.Empty;
            if (this.Request.Params.AllKeys.Contains("code"))
            {
                string code = this.Request.Params["code"];
                if (code.IsNotNullAndEmpty() && code == "1")
                {
                    msg = "用户不具备足够的权限,请更换用户重新登录";
                }
            }
            LogonViewModel ViewModel = new LogonViewModel
            {
                Title = "登录",
                Message = msg,
                MasterViewModel = this.MasterViewModel
            };
            return this.Result(ViewModel);
        }

        [HttpPost]
        [SecurityAppFilter(PageControllerItems.LogonController)]
        public ActionResult LogOn(LogonModel model, string returnUrl)
        {
            IAccountContract AccountContract = Actor.Public.AsAccountManager();
            if (AccountContract.ValidateUser(model.UserName, AccountContract.EncryptPassword(model.Password)))
            {
                BzureUser user = AccountContract.GetUserByName(model.UserName);

                user.SignIn(model.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return Redirect("/");
                }
            }
            else
            {
                LogonViewModel ViewModel = new LogonViewModel()
                {
                    Title = "用户登录",
                    Message = "用户名或密码不正确",
                    MasterViewModel = this.MasterViewModel
                };
                return this.Result(ViewModel);

            }
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************
        [SecurityAppFilter(PageControllerItems.LogoffController)]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Actor.Me.SignOut();
            return Redirect("/");
        }
        [AccountRegisterAuthorizeFilter]
        [SecurityAppFilter(PageControllerItems.RegisterController)]
        public ActionResult Register()
        {
            RegisterViewModel ViewModel = new RegisterViewModel()
            {
                Title = "注册",
                MasterViewModel = this.MasterViewModel
            };
            return this.Result(ViewModel);
        }

        [HttpPost]
        [AccountRegisterAuthorizeFilter]
        [SecurityAppFilter(PageControllerItems.RegisterController)]
        public ActionResult Register(RegisterModel model)
        {
            IAccountContract ac = Actor.Public.AsAccountManager();
            IUserContract uc = Actor.Public.AsUserManager();
            BzureUser user = new BzureUser(uc.GenerateUserID (), model.UserName)
            {
                EMail = model.Email,
                Password = ac.EncryptPassword(model.Password),
                RoleValue = 0,
                OpenID = string.Empty,
                State = 0,
                NickName = model.UserName
            };
            CreateUserResult result = ac.CreateUser(user);
            if (result == CreateUserResult.Success)
            {
                user.SignIn(false);//登录

                return Redirect("/");
            }
            else
            {
                RegisterViewModel ViewModel = new RegisterViewModel()
                {
                    Title = "注册",
                    Message = result.StringValue(),
                    MasterViewModel = this.MasterViewModel
                };
                return this.Result(ViewModel);

            }

        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        [SecurityAppFilter(PageControllerItems.ChangePasswordController)]
        public ActionResult ChangePassword()
        {
            ChangePasswordViewModel ViewModel = new ChangePasswordViewModel()
            {
                Title = "修改密码",
                UserName = Actor.Me.Principal.Identity.Name,
                MasterViewModel = this.MasterViewModel
            };
            return Result(ViewModel);
        }
        [Authorize]
        [HttpPost]
        [SecurityAppFilter(PageControllerItems.ChangePasswordController)]
        public ActionResult ChangePassword(ChangePasswordModel model, string returnUrl)
        {
            if (!Actor.Public.IsAuthenticated)
            {
                return RedirectToAction("Logon");
            }
            Bzure.Security.IAccountContract AccountContract = Actor.Public.AsAccountManager();
            if (AccountContract.ValidateUser(Actor.Me.Principal.Identity.Name, AccountContract.EncryptPassword(model.OldPassword)))
            {
                string msg = string.Empty;
                if (AccountContract.SetPassword(Actor.Me.Principal.Identity.Name, AccountContract.EncryptPassword(model.NewPassword)))
                {
                    msg = "密码修改成功";
                }
                else
                {
                    msg = "密码修改失败，请重试";
                }

                ChangePasswordViewModel ViewModel = new ChangePasswordViewModel()
                {
                    Title = "修改密码",
                    UserName = Actor.Me.Principal.Identity.Name,
                    MasterViewModel = this.MasterViewModel,
                    Message = msg
                };
                return Result(ViewModel);
            }
            else
            {
                return RedirectToAction("Logon");
            }
        }
    }
}
